<template>
  <view class="page">
    <!-- 状态卡片 -->
    <view class="status-card" :style="{ background: getStatusGradient(order.status) }">
      <text class="status-icon">{{ getStatusIcon(order.status) }}</text>
      <text class="status-text">{{ getStatusText(order.status) }}</text>
      <text class="status-desc">{{ getStatusDesc(order.status) }}</text>
      <!-- 取消/退款原因 -->
      <view class="cancel-reason" v-if="showCancelReason">
        <text class="reason-label">{{ cancelReasonLabel }}：</text>
        <text class="reason-text">{{ order.cancelReason }}</text>
      </view>
    </view>

    <!-- 收货地址 -->
    <view class="section address-section" v-if="order.deliveryAddress">
      <view class="section-title">
        <text class="title-icon">📍</text>
        <text class="title-text">收货地址</text>
      </view>
      <view class="address-content">
        <text class="address-text">{{ order.deliveryAddress }}</text>
      </view>
    </view>

    <!-- 商品信息 -->
    <view class="section goods-section">
      <view class="section-title">
        <text class="title-icon">📦</text>
        <text class="title-text">商品信息</text>
      </view>
      <view class="goods-item" v-for="(item, index) in order.items" :key="index">
        <image 
          class="goods-image" 
          :src="item.productImage || '/static/images/product-default.png'"
          mode="aspectFill"
        ></image>
        <view class="goods-info">
          <text class="goods-name">{{ item.productName }}</text>
          <view class="goods-footer">
            <text class="goods-price">¥{{ item.price }}</text>
            <text class="goods-quantity">x{{ item.quantity }}</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 用户信息（仅商家可见） -->
    <view class="section user-section" v-if="isMerchant">
      <view class="section-title">
        <text class="title-icon">👤</text>
        <text class="title-text">用户信息</text>
      </view>
      <view class="info-item" v-if="order.userName">
        <text class="info-label">用户姓名</text>
        <text class="info-value">{{ order.userName }}</text>
      </view>
      <view class="info-item" v-if="order.userPhone">
        <text class="info-label">联系电话</text>
        <text class="info-value">{{ order.userPhone }}</text>
      </view>
      <view class="info-item" v-if="order.userId">
        <text class="info-label">用户ID</text>
        <text class="info-value">{{ order.userId }}</text>
      </view>
    </view>

    <!-- 订单信息 -->
    <view class="section order-section">
      <view class="section-title">
        <text class="title-icon">📄</text>
        <text class="title-text">订单信息</text>
      </view>
      <view class="info-item">
        <text class="info-label">订单号</text>
        <text class="info-value">{{ order.orderNo }}</text>
      </view>
      <view class="info-item">
        <text class="info-label">订单类型</text>
        <text class="info-value">{{ getOrderTypeText(order.orderType) }}</text>
      </view>
      <view class="info-item">
        <text class="info-label">订单状态</text>
        <text class="info-value">{{ getStatusText(order.status) }}</text>
      </view>
      <view class="info-item">
        <text class="info-label">下单时间</text>
        <text class="info-value">{{ order.createTime }}</text>
      </view>
      <view class="info-item" v-if="order.payTime">
        <text class="info-label">支付时间</text>
        <text class="info-value">{{ order.payTime }}</text>
      </view>
      <view class="info-item" v-if="order.acceptTime">
        <text class="info-label">接单时间</text>
        <text class="info-value">{{ order.acceptTime }}</text>
      </view>
      <view class="info-item" v-if="order.finishTime">
        <text class="info-label">完成时间</text>
        <text class="info-value">{{ order.finishTime }}</text>
      </view>
      <view class="info-item" v-if="order.remark">
        <text class="info-label">订单备注</text>
        <text class="info-value">{{ order.remark }}</text>
      </view>
      <view class="info-item" v-if="order.cancelReason">
        <text class="info-label">取消/退款原因</text>
        <text class="info-value">{{ order.cancelReason }}</text>
      </view>
    </view>

    <!-- 费用明细 -->
    <view class="section fee-section">
      <view class="section-title">
        <text class="title-icon">💰</text>
        <text class="title-text">费用明细</text>
      </view>
      <view class="fee-item">
        <text class="fee-label">商品金额</text>
        <text class="fee-value">¥{{ order.totalAmount }}</text>
      </view>
      <view class="fee-item">
        <text class="fee-label">配送费</text>
        <text class="fee-value">+¥{{ order.deliveryFee || 0 }}</text>
      </view>
      <view class="fee-item" v-if="order.discountAmount > 0">
        <text class="fee-label">优惠金额</text>
        <text class="fee-value">-¥{{ order.discountAmount }}</text>
      </view>
      <view class="fee-item total">
        <text class="fee-label">实付金额</text>
        <text class="fee-value highlight">¥{{ order.actualAmount }}</text>
      </view>
    </view>

    <!-- 底部操作栏 -->
    <view class="bottom-bar" v-if="showActions">
      <!-- 待支付：取消订单 + 立即支付 -->
      <view class="btn btn-default" v-if="order.status === 0" @click="cancelOrder">取消订单</view>
      <view class="btn btn-primary" v-if="order.status === 0" @click="payOrder">立即支付</view>
      
      <!-- 待接单：申请退款 -->
      <view class="btn btn-default" v-if="order.status === 1" @click="applyRefund">申请退款</view>
      
      <!-- 配送中：申请退款 + 确认收货 -->
      <view class="btn btn-default" v-if="order.status === 3 && canApplyRefund" @click="applyRefund">申请退款</view>
      <view class="btn btn-primary" v-if="order.status === 3" @click="confirmReceive">确认收货</view>
      
      <!-- 退款审核中：查看退款状态 -->
      <view class="btn btn-default" v-if="order.status === 9" @click="viewRefundStatus">查看退款状态</view>
      
      <!-- 已完成：再来一单 -->
      <view class="btn btn-default" v-if="order.status === 6" @click="buyAgain">再来一单</view>
    </view>

    <!-- 商家快捷操作 -->
    <view class="bottom-bar" v-if="showMerchantActions">
      <view class="btn btn-primary" @click="finishOrderAsMerchant">确认收货</view>
    </view>
  </view>
</template>

<script>
import { 
  getOrderStatusDisplay,
  getStatusGradient,
  getOrderTypeText
} from '@/utils/orderStatus'
import { mapGetters } from 'vuex'

export default {
  data() {
    return {
      orderId: null,
      order: {
        items: [],
        orderType: 1  // 默认零食订单
      }
    }
  },
  computed: {
    ...mapGetters('user', ['userType']),
    // 是否是商家
    isMerchant() {
      return this.userType === 3
    },
    showActions() {
      // 商家不显示操作按钮（商家在自己的订单管理页操作）
      if (this.isMerchant) {
        return false
      }
      // 普通用户：待支付、待接单、配送中、退款审核中、已完成显示操作按钮
      return [0, 1, 3, 6, 9].includes(this.order.status)
    },
    showMerchantActions() {
      return this.isMerchant && this.order.orderType === 1 && this.order.status === 3
    },
    // 是否可以申请退款
    canApplyRefund() {
      // 零食订单：配送中可以申请退款（需要配置允许）
      // 代取订单：待取件、配送中可以申请退款
      if (this.order.orderType === 1) {
        // 零食订单配送中退款需要系统配置允许
        return true // 暂时允许，后续可通过配置控制
      } else {
        // 代取订单（2,3,4）待取件、配送中都可以退款
        return [2, 3].includes(this.order.status)
      }
    },
    showCancelReason() {
      if (!this.order.cancelReason) return false
      return [5, 7, 8, 9].includes(this.order.status)
    },
    cancelReasonLabel() {
      if (this.order.status === 8) {
        return '退款原因'
      }
      if (this.order.status === 9) {
        return '退款说明'
      }
      return '取消原因'
    }
  },
  onLoad(options) {
    if (options.id) {
      this.orderId = options.id
      this.loadOrderDetail()
    }
  },
  methods: {
    async loadOrderDetail() {
      try {
        uni.showLoading({ title: '加载中...' })
        const { getOrderDetail } = require('@/api/order')
        const order = await getOrderDetail(this.orderId)
        
        //console.log('订单详情:', order)
        
        this.order = order
        uni.hideLoading()
      } catch (error) {
        console.error('加载订单详情失败:', error)
        uni.hideLoading()
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        })
        
        setTimeout(() => {
          uni.navigateBack()
        }, 1500)
      }
    },
    
    getOrderTypeText(orderType) {
      return getOrderTypeText(orderType)
    },
    
    getStatusIcon(status) {
      // 确保 orderType 和 status 有效
      const orderType = this.order.orderType || 1
      const display = getOrderStatusDisplay(orderType, status)
      return display.icon
    },
    
    getStatusText(status) {
      // 确保 orderType 和 status 有效
      const orderType = this.order.orderType || 1
      const display = getOrderStatusDisplay(orderType, status)
      return display.text
    },
    
    getStatusDesc(status) {
      // 确保 orderType 和 status 有效
      const orderType = this.order.orderType || 1
      const display = getOrderStatusDisplay(orderType, status)
      return display.desc || display.description || ''
    },
    
    getStatusGradient(status) {
      const orderType = this.order.orderType || 1
      return getStatusGradient(orderType, status)
    },
    
    async cancelOrder() {
      // 判断是待支付还是待接单
      const isPaid = this.order.status === 1
      const title = isPaid ? '申请退款' : '取消订单'
      const content = isPaid ? '确认申请退款吗？' : '确认取消订单吗？'
      
      uni.showModal({
        title: title,
        content: content,
        editable: true,
        placeholderText: isPaid ? '请输入退款原因（选填）' : '请输入取消原因（选填）',
        success: async (res) => {
          if (res.confirm) {
            try {
              uni.showLoading({ title: '处理中...' })
              
              const { cancelOrder } = require('@/api/order')
              const reason = res.content || (isPaid ? '不想要了' : '不想要了')
              await cancelOrder(this.orderId, reason)
              
              uni.hideLoading()
              uni.showToast({
                title: isPaid ? '退款成功' : '已取消',
                icon: 'success'
              })
              
              // 重新加载订单详情
              setTimeout(() => {
                this.loadOrderDetail()
              }, 1500)
            } catch (error) {
              console.error('取消订单失败:', error)
              uni.hideLoading()
              uni.showToast({
                title: error.message || '操作失败',
                icon: 'none'
              })
            }
          }
        }
      })
    },
    
    async payOrder() {
      uni.redirectTo({
        url: `/pages/order/payment?orderId=${this.orderId}&orderNo=${this.order.orderNo}&amount=${this.order.actualAmount}`
      })
    },
    
    async confirmReceive() {
      uni.showModal({
        title: '确认收货',
        content: '确认已收到商品吗？',
        success: async (res) => {
          if (res.confirm) {
            try {
              uni.showLoading({ title: '确认中...' })
              const { confirmOrder } = require('@/api/order')
              await confirmOrder(this.orderId)
              
              uni.hideLoading()
              uni.showToast({
                title: '已确认收货',
                icon: 'success'
              })
              
              // 重新加载订单详情
              setTimeout(() => {
                this.loadOrderDetail()
              }, 1500)
            } catch (error) {
              console.error('确认收货失败:', error)
              uni.hideLoading()
              uni.showToast({
                title: error.message || '操作失败',
                icon: 'none'
              })
            }
          }
        }
      })
    },
    
    async finishOrderAsMerchant() {
      uni.showModal({
        title: '确认完成订单',
        content: '确定要为用户确认收货并完成订单吗？',
        success: async (res) => {
          if (res.confirm) {
            try {
              uni.showLoading({ title: '处理中...' })
              const { finishOrder } = require('@/api/order')
              await finishOrder(this.orderId)
              uni.hideLoading()
              uni.showToast({
                title: '订单已完成',
                icon: 'success'
              })
              setTimeout(() => {
                this.loadOrderDetail()
              }, 1200)
            } catch (error) {
              console.error('商家确认收货失败:', error)
              uni.hideLoading()
              uni.showToast({
                title: error.message || '操作失败',
                icon: 'none'
              })
            }
          }
        }
      })
    },
    
    async buyAgain() {
      try {
        const orderType = this.order?.orderType || 1
        if (orderType !== 1) {
          uni.showToast({ title: '该类型暂不支持再来一单', icon: 'none' })
          return
        }
        uni.showLoading({ title: '生成中...' })
        const { getReorderItems } = require('@/api/order')
        const list = await getReorderItems(this.orderId)
        uni.hideLoading()
        const items = Array.isArray(list) ? list : []
        if (items.length === 0) {
          uni.showToast({ title: '商品均已下架或无库存', icon: 'none' })
          return
        }
        const itemsParam = encodeURIComponent(JSON.stringify(items))
        uni.navigateTo({ url: `/pages/order/confirm?from=detail&items=${itemsParam}` })
      } catch (error) {
        console.error('再来一单失败:', error)
        uni.hideLoading()
        uni.showToast({ title: (error && error.message) ? error.message : '生成失败，请稍后再试', icon: 'none' })
      }
    },

    // 申请退款
    applyRefund() {
      //console.log('申请退款，orderId:', this.orderId)
      if (!this.orderId) {
        uni.showToast({
          title: '订单ID不能为空',
          icon: 'none'
        })
        return
      }
      uni.navigateTo({
        url: `/pages/order/refund-apply?orderId=${this.orderId}`
      })
    },

    // 查看退款状态
    viewRefundStatus() {
      //console.log('查看退款状态，orderId:', this.orderId)
      if (!this.orderId) {
        uni.showToast({
          title: '订单ID不能为空',
          icon: 'none'
        })
        return
      }
      uni.navigateTo({
        url: `/pages/order/refund-status?orderId=${this.orderId}`
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.page {
  min-height: 100vh;
  background: #f5f7fa;
  padding-bottom: 180rpx;
}

/* 状态卡片 */
.status-card {
  padding: 60rpx 32rpx;
  text-align: center;
  color: #fff;
  
  .status-icon {
    font-size: 100rpx;
    display: block;
    margin-bottom: 24rpx;
  }
  
  .status-text {
    font-size: 36rpx;
    font-weight: bold;
    display: block;
    margin-bottom: 12rpx;
  }
  
  .status-desc {
    font-size: 24rpx;
    opacity: 0.9;
    display: block;
  }
  
  .cancel-reason {
    margin-top: 20rpx;
    padding: 16rpx 20rpx;
    background: rgba(255, 255, 255, 0.2);
    border-radius: 12rpx;
    display: flex;
    flex-direction: column;
    gap: 8rpx;
    text-align: left;
    
    .reason-label {
      font-size: 22rpx;
      color: rgba(255, 255, 255, 0.8);
      font-weight: bold;
    }
    
    .reason-text {
      font-size: 24rpx;
      color: rgba(255, 255, 255, 0.95);
      line-height: 1.5;
    }
  }
}

/* 通用section */
.section {
  background: #fff;
  margin-top: 20rpx;
  padding: 32rpx;
}

.section-title {
  display: flex;
  align-items: center;
  gap: 12rpx;
  margin-bottom: 24rpx;
  
  .title-icon {
    font-size: 32rpx;
  }
  
  .title-text {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
  }
}

/* 地址section */
.address-content {
  padding: 24rpx;
  background: #f5f7fa;
  border-radius: 12rpx;
  
  .address-text {
    font-size: 26rpx;
    color: #666;
    line-height: 1.8;
  }
}

/* 商品section */
.goods-item {
  display: flex;
  gap: 20rpx;
  padding: 20rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
  
  &:last-child {
    border-bottom: none;
  }
}

.goods-image {
  width: 120rpx;
  height: 120rpx;
  border-radius: 12rpx;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
}

.goods-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.goods-name {
  font-size: 28rpx;
  color: #333;
  line-height: 1.4;
}

.goods-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.goods-price {
  font-size: 28rpx;
  color: #ff4d4f;
  font-weight: bold;
}

.goods-quantity {
  font-size: 26rpx;
  color: #999;
}

/* 订单信息section */
.info-item {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  padding: 16rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
  
  &:last-child {
    border-bottom: none;
  }
}

.info-label {
  font-size: 26rpx;
  color: #999;
  width: 160rpx;
  flex-shrink: 0;
}

.info-value {
  flex: 1;
  font-size: 26rpx;
  color: #333;
  text-align: right;
  word-break: break-all;
}

/* 费用section */
.fee-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16rpx 0;
  
  &.total {
    padding-top: 24rpx;
    border-top: 1rpx solid #f0f0f0;
    margin-top: 16rpx;
  }
}

.fee-label {
  font-size: 28rpx;
  color: #666;
}

.fee-value {
  font-size: 28rpx;
  color: #333;
  
  &.highlight {
    font-size: 36rpx;
    color: #ff4d4f;
    font-weight: bold;
  }
}

/* 底部操作栏 */
.bottom-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: #fff;
  padding: 24rpx;
  box-shadow: 0 -4rpx 12rpx rgba(0, 0, 0, 0.05);
  display: flex;
  justify-content: flex-end;
  gap: 24rpx;
  z-index: 100;
}

.btn {
  padding: 20rpx 48rpx;
  border-radius: 40rpx;
  font-size: 28rpx;
  
  &.btn-default {
    background: #f5f5f5;
    color: #666;
  }
  
  &.btn-primary {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: #fff;
    font-weight: bold;
  }
}
</style>
